//
//  CZOauthViewController.swift
//  GZWeiboMing
//
//  Created by 1 on 16/3/27.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit

import SVProgressHUD

class CZOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //没有背景颜色，在Modal的时候只看得到的导航栏
        view.backgroundColor = UIColor.whiteColor()
        
        //设置导航栏
        setupNavigationBar()
        
        //使用webView加载登录界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        SVProgressHUD.showWithStatus("正在加载",maskType: SVProgressHUDMaskType.None)
    }
    
    ///设置导航栏
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    // document.getElementById('userId').value='17806743623'
    // document.getElementById('passwd').value='LUyunfeng520'
    ///点击方法
    @objc private func autoFill(){
        let jsCode = "document.getElementById('userId').value='17806743623';document.getElementById('passwd').value='LUyunfeng520'"
        //执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    
    //关闭控制器
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
}


//MARK: - 扩展
extension CZOauthViewController: UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //webView是否需要加载某个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        print("urlString:\(urlString)")
        // 不是授权回调地址，让他加载
        if !urlString.hasPrefix(redirect_uri) {
            return true
        }else {
            let query = request.URL?.query
           
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                let nsQuery = query! as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("code:\(code)")
                loadAccessToken(code)
            }else {
                close()
            }
            return false
        }
    }
    ///加载 access_token, post
    func loadAccessToken(code: String) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //拼接参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        CZNetworkTool.sharedInstance.afnManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                print("result: \(result)")
            }) { (_, error) -> Void in
                print("请求accesstoken失败 \(error)")
        }
    }
 
}










